<?php
require "db_creds.inc";


/* 
Studenkel funksjoner
Eirik Kvarstein
1:42 PM 9/5/2013


Funksjoner:

connect();	   			  	-Åpner database kobling ( trenger ikke tenke på denne, connect() blir kalt automatisk ).
login("test", "123);		-Returnerer 0 om passordet og brukernavnet er feil, ellers > 0 
register("test", "123");	-Opretter ny bruker. Sjekker også om brukernavnet er tilgjengelig først.
isAdmin("test")				-returnerer 1 om bruker er admin, 0 om bruker IKKE er admin.
*/



/* 
 ######################################################################################
 connect
 ######################################################################################
 
 Åpner kobling til mysqli databasen på boltit.uia.no
 
 Siden mysqli objektet brukes i alle funksjonene, må det være globalt. ( global variables ).
 
 */

function connect(){  
 /* Create a new mysqli object with database connection parameters */
	// Fjerna DB passord for sikkerhets skyld. ligger åpent for alle på googlecode å lese.
	global $mysqli;
	global $_dbUser;
	global $_dbPw;
   $mysqli = new mysqli('localhost', $_dbUser, $_dbPw, 'studenkel');

   if(mysqli_connect_errno()) {
      echo "Connection Failed: " . mysqli_connect_errno();
      exit();
   }

 }
 
 
/* 
 ######################################################################################
 LOG IN
 ######################################################################################
 
 Returnerer ID fra mysql. Hvis ID ikke er 0 er brukernavn og passord godkjent. 
 feks:
 
 if(login("admin", "test") > 0){
  // riktig passord, oprett session
  $_SESSION['user'] = $user;
 }
 
 
 */
function login($username, $password){
global $mysqli;
connect(); // åpne database
   
   /* Create a prepared statement */
   /*
   
   SQL som henter ID fra tabellen studenkel_users, hvor brukernavn og passord matcher med parameterne.
   Så hvis brukernavn og passord matcher, så hentes ID fra den raden, ellers er id 0
   
   i bind_param blir $user og $pass bundet til user=? og password=PASSWORD(?).
   PASSWORD() er en SQL funksjon som krypterer, så det sjekkes mot en kryptert versjon av passordet brukerern gir.
   
   */
   if($stmt = $mysqli -> prepare("SELECT id FROM studenkel_users WHERE username=? AND password=OLD_PASSWORD(?)")) {

      // Bind parameters
      $stmt -> bind_param("ss", $username, $password);

      /* Execute it */
      $stmt -> execute();

      /* Bind results */
      $stmt -> bind_result($result);

      /* Fetch the value */
      $stmt -> fetch();

      //echo "Request returned id: ". $result;
		return $result;
	  
      /* Close statement */
      $stmt -> close();
   }



    /* Close connection */
   $mysqli -> close();
}


// Sjekke om bruker er admin, returnerer 1 om admin, 0 om vanlig bruker
function isAdmin($user){
global $mysqli;
connect(); // åpne database
   
   /* Create a prepared statement */
   /*
   
   SQL som henter ID fra tabellen studenkel_users, hvor brukernavn og passord matcher med parameterne.
   Så hvis brukernavn og passord matcher, så hentes ID fra den raden, ellers er id 0
   
   i bind_param blir $user og $pass bundet til user=? og password=PASSWORD(?).
   PASSWORD() er en SQL funksjon som krypterer, så det sjekkes mot en kryptert versjon av passordet brukerern gir.
   
   */
   if($stmt = $mysqli -> prepare("SELECT admin FROM studenkel_users WHERE username=?")) {

      // Bind parameters
      $stmt -> bind_param("s", $user);

      /* Execute it */
      $stmt -> execute();

      /* Bind results */
      $stmt -> bind_result($result);

      /* Fetch the value */
      $stmt -> fetch();

      //echo "Request returned id: ". $result;
		return $result;
	  
      /* Close statement */
      $stmt -> close();
}



    /* Close connection */
   $mysqli -> close();

}

/*

hente ut linker til checkboxene i settings.php 
hvor bruker kan definere prefs-

trenger: id, title
*/

function getLinkSettings($gruppe){
global $mysqli;
connect();
 
 $prefs = "";
 
  // hente linkid fra userprefs inn i et array..
  // var_dump($prefs) = string(23) "[13][21][14][4][19][23]"
 if($stmt = $mysqli -> prepare("select p.linkid FROM studenkel_userprefs as p WHERE p.usr=?")){
 $stmt -> bind_param("s", $_SESSION['user']);
 $stmt -> execute();
 $stmt ->bind_result($result);
	while($stmt -> fetch()) {
	$prefs = $prefs."[".$result."]"; /* legger til [linkid] i stringen $prefs*/
	}

 $stmt -> close();
 } else { die ("Mysql error i getLinkSettings::hente array for userprefs: ".$mysqli->error); } 
 
 //var_dump($prefs);
 
 // Hente id og title fra studenkel_content hvor gruppe er $gruppe
 if($stmt = $mysqli -> prepare("select c.id, c.title FROM studenkel_content as c where c.gruppe = ?")){
 $stmt -> bind_param("s", $gruppe);
 $stmt -> execute();
 $stmt -> bind_result($id, $title);

	//loope gjennom radene i studenkel_content
	while ($stmt->fetch()){
		//lage checkboxer OG sette checked hvis id finnes i $prefs
		if(strstr($prefs, "[".$id."]")){ /* hvis [id] finnes i $prefs, sett checked */
		echo "<input type=\"checkbox\" name=\"Lenke[]\" value=$id id=$id checked>$title<br>\n";
		}
		else { /* hvis id ikke finnes i $prefs, sett unchecked. */
		echo "<input type=\"checkbox\" name=\"Lenke[]\" value=$id id=$id>$title<br>\n";
		}
	}
 $stmt -> close();
 }
 else {
 die("Mysqli feil i getLinkSettings():: ".$mysqli->error);
 }
 
     /* Close connection */
   $mysqli -> close();
}

/* saveLinkSettings()

Lagre bruker definerte valg i DB

*/
function saveLinkSettings($user, $prefs){
global $mysqli;
connect();

// Drop old user prefs..
  if($stmt = $mysqli -> prepare("DELETE from studenkel_userprefs WHERE usr = ?")){
	$stmt -> bind_param("s", $user);
	$stmt -> execute();
	$stmt -> close();
	} 
 
//insert new prefs
 if($stmt = $mysqli -> prepare("INSERT into studenkel_userprefs(usr,linkid) VALUES(?, ?)")){
 
	//loope gjennom array og lagre alle link id'ene.
	foreach($prefs as $rad){
 $stmt -> bind_param("ss", $user, $rad);
 $stmt -> execute();
 }
 $stmt -> close();
 }
 else {
 die("Mysqli feil i saveLinkSettings():: ".$mysqli->error);
 }
 
     /* Close connection */
   $mysqli -> close();
}



/*
 ######################################################################################
 HENTE STATS
 ######################################################################################
*/
function getStats(){
global $mysqli;
connect();

$sql = 'SELECT (

SELECT SUM( p.views ) 
FROM studenkel_userprefs AS p
) AS  `views` , (

SELECT COUNT( c.id ) 
FROM studenkel_content AS c
) AS  `content_count` , (

SELECT COUNT( u.id ) 
FROM studenkel_users AS u
) AS  `user_count`';


 // Hente summen av alle views feltene i studenkel_userprefs, antall id'er i content, og antall id'er i users 
 if($stmt = $mysqli -> prepare($sql)){
 $stmt -> execute();
 $stmt -> bind_result($views, $links, $users);
 $stmt -> fetch();
 $stmt -> close();
 }

echo "Totale antall lenke klikk: $views<br>";
echo "Antall lenker: $links<br>";
echo "Antall brukere: $users<br>";

     /* Close connection */
   $mysqli -> close();
}



/*
	saveMyLink() - Lagrer brukers personlige lenke
*/
function saveMyLink($user, $title, $url, $host){
global $mysqli;
connect(); // åpner DB

$sql = "INSERT into studenkel_userlinks(user, title, url, host) VALUES(?, ?, ?, ?)";
	if($stmt = $mysqli -> prepare($sql)){
	$stmt -> bind_param("ssss", $user, $title, $url, $host);
	$stmt -> execute();
	$stmt -> close();
	}


    /* Close connection */
   $mysqli -> close();
}


/*
	deleteMyLink - SLetter brukers url fra studenkel_userlinks
*/
function deleteMyLink($user, $id){
global $mysqli;
connect(); // åpner DB

//Sjekk om brukeren eier lenken. ( om ingen bare har kjørt del.php?uid=[random nummer] )
$stmt = $mysqli -> prepare("SELECT user FROM studenkel_userlinks WHERE id=?");
$stmt -> bind_param("i", $id);
$stmt -> execute();
$stmt -> bind_result($result);
$stmt -> fetch();
$stmt -> close();

//hvis user fra DB stemmer med user fra Session, kjør på.
if($user == $result){
$sql = "DELETE FROM studenkel_userlinks WHERE id = ? AND user = ?";
	if($stmt = $mysqli -> prepare($sql)){
	$stmt -> bind_param("is", $id, $user);
	$stmt -> execute();
	$stmt -> close();
	header("Location: index.php");
	}

}
// Om brukeren prøvde å slette noen andres private lenker
else {
echo "Du driver med? Ip logged.";
NSALog($user, "Attempted to delete ".$result."'s personal link ($id)");

}

    /* Close connection */
   $mysqli -> close();
}



/*
	getMyLinks() - Henter brukernes lenker fra studenkel_userlinks
*/
function getMyLinks($user){
global $mysqli;
connect(); // åpne DB

// SQL for å hente bruker sine personlige lenker
$sql = "SELECT title, url, host, id FROM studenkel_userlinks WHERE user=? ORDER BY views DESC";
 
 if($stmt = $mysqli -> prepare($sql)){
 $stmt -> bind_param("s", $user);
 $stmt -> execute();
 $stmt -> bind_result($title, $url, $host, $id);
 
 //lag table
 echo "<div id=\"userlinks\"><table>";
 
 // Loope igjennom resultat radene
 while($stmt -> fetch()){
 echo "<tr><td><a href=\"del.php?uid=$id\"><img src=\"bilder/del.png\" width=20px height=20px title=Slett alt=Slett></a></td><td><img src=images/$host.ico width=32px height=32px></td><td><td><b><a href=\"$url\" target=\"_blank\">$title</a></b>  <span style=\"font-size:60%\">$url</span></td></tr>\n";
 }
 
 //avslutt table
 echo "</table></div>";
 $stmt -> close();
 }



     /* Close connection */
   $mysqli -> close();

}


/*
 ######################################################################################
 HENT UT LINKER
 ######################################################################################
*/
function getLinks($gruppe){
global $mysqli;
connect();
 
 $logged_in = 0;
 
 // Om brukeren er logget inn, hent brukers valgte linker ( id i userprefs ) og sorter på views.
 if(isset($_SESSION['user'])){
 $logged_in = 1;
 //$sql = "SELECT title, url, img, description FROM studenkel_content WHERE gruppe= ? AND WHERE id IN (select linkid FROM studenkel_prefs WHERE usr = ?)";
 $sql = "SELECT c.title, c.id, c.img, c.description FROM studenkel_content as c, studenkel_userprefs as p WHERE p.usr = ? and p.linkid = c.id and c.gruppe = ? ORDER BY p.views DESC";
 
 }
 // Hvis ikke bruker er logget inn, hent alt.
 else {
 $logged_in = 0;
 $sql = "SELECT title, id, img, description FROM studenkel_content WHERE gruppe=?";
 }
 
 if($stmt = $mysqli -> prepare($sql)){
	if($logged_in == 1)
	$stmt -> bind_param("ss",$_SESSION['user'], $gruppe);
 
	if($logged_in == 0)
	$stmt -> bind_param("s", $gruppe);
 
 $stmt -> execute();
 $stmt -> bind_result($title, $id,$img,$desc);

	//loope gjennom radene i studenkel_content
	while ($stmt->fetch()){
	echo "<a href=\"redirect.php?id=". $id ."\" target=\"_blank\" onMouseOver=\"overlay('". $desc ."')\" onMouseOut=\"overlay('')\"><div id=\"linkbox\" style=\"background-image: url('images/".$img."');\"><h3>". $title. "</h3></div></a>\n";
	}
 $stmt -> close();
 }
 else {
 die("Mysqli feil i getLinks():: ".$mysqli->error);
 }
 
     /* Close connection */
   $mysqli -> close();
}


/* urlClick()

returnerer URL til ID, Og oppdater userprefs views med +1

*/
function urlClick($id, $user){
global $mysqli;
connect();

// Hvis $user ikke er 0
if($user != "0"){
// Oppdater views
  if($stmt = $mysqli -> prepare("UPDATE studenkel_userprefs set views = views+1 WHERE usr = ? AND linkid = ?")){
	$stmt -> bind_param("si", $user, $id);
	$stmt -> execute();
	$stmt -> close();
	} 
}
 
// Hent URL (linkid og id er samme )
 if($stmt = $mysqli -> prepare("SELECT url FROM studenkel_content WHERE id = ?")){
 $stmt -> bind_param("i",$id);
 $stmt -> execute();
 $stmt -> bind_result($url);
 $stmt -> fetch();
 $stmt -> close();
 
 }
 else {
 die("Mysqli feil i urlClick():: ".$mysqli->error);
 }
 
     /* Close connection */
   $mysqli -> close();
	
	//returner link URL
    return $url;
   }


/*
 ######################################################################################
 HENT UT LOGG
 ######################################################################################
*/
function getLog(){
global $mysqli;
connect();
 
 if($stmt = $mysqli -> prepare("SELECT date,action,user,ip FROM studenkel_log ORDER BY date DESC LIMIT 50")){
 $stmt -> execute();
 $stmt -> bind_result($date, $action,$user,$ip);

	
	// start table
	echo "<table><tr><td>Dato</td><td>Bruker</td><td>Handling</td><td>IP</td></tr>\n";
	//loope gjennom radene i studenkel_content
	while ($stmt->fetch()){
	echo "<tr><td>$date</td><td>$user</td><td>$action</td><td>$ip</td></tr>\n";
	}
	//avslutt table
	echo "</table>\n";
 $stmt -> close();
 }
 
     /* Close connection */
   $mysqli -> close();
}

function getUsers(){
global $mysqli;
connect();
 
 if($stmt = $mysqli -> prepare("SELECT username,admin FROM studenkel_users ORDER BY admin DESC, username ASC")){
 $stmt -> execute();
 $stmt -> bind_result($user,$admin);

	
	// start table
	echo "<table align=\"center\"><tr><td><b>Brukere</b></td></tr>";
	//loope gjennom radene i studenkel_content
	while ($stmt->fetch()){
	if($admin == 1){ //hvis bruker er admin, får han en stjerne ved navnet. ( &#9733 )
	echo "<tr><td><a href=\"profile.php?id=$user\">$user &#9733;</a></td></tr>\n";
	}
	else {
	echo "<tr><td><a href=\"profile.php?id=$user\">$user</a></td></tr>\n";
	}
	}
	//avslutt table
	echo "</table>\n";
 $stmt -> close();
 }
 
     /* Close connection */
   $mysqli -> close();
}


/*
 ######################################################################################
 getUserInfo() Henter info fra studenkel_userprofile
 ######################################################################################
*/
function getUserInfo($user){
global $mysqli;
connect();
 //$info, $user, $studie, $img, $fornavn, $etternavn, $hjemmeside
 if($stmt = $mysqli -> prepare("SELECT om_meg, fornavn, etternavn, studieretning, bilde, hjemmeside FROM studenkel_userprofile WHERE user = ?")){
	$stmt -> bind_param("s", $user); 
	$stmt -> execute();
	 $stmt -> bind_result($info, $fornavn, $etternavn, $studie, $img, $hjemmeside);
	$stmt -> fetch();
	//lage array fra verdiene
	$userinfo = array(
	"fornavn" => $fornavn,
	"etternavn" => $etternavn,
	"studie" => $studie,
	"bilde" => $img,
	"hjemmeside" => $hjemmeside,
	"om_meg" => $info,
	);

 $stmt -> close();
 }
else {
die("Mysql error i getUserInfo: ".$mysqli->error);
}
 
	//returner arrayet
	return $userinfo;

     /* Close connection */
   $mysqli -> close();
}

function getSkins(){
global $mysqli;
connect();
 
 if($stmt = $mysqli -> prepare("SELECT name FROM studenkel_skins ORDER BY id")){
 $stmt -> execute();
 $stmt -> bind_result($name);

	//loope gjennom radene i studenkel_content
	while ($stmt->fetch()){
	echo "<option>$name</option>";
	}
 $stmt -> close();
 }
 
     /* Close connection */
   $mysqli -> close();
}


/*
 ######################################################################################
 HENT UT URLER OG FORMATERE FOR REDIGERING ( I TABELL )
 ######################################################################################
*/
function editLinks(){
global $mysqli;
connect();
 
 if($stmt = $mysqli -> prepare("SELECT id, title, url,img, op FROM studenkel_content")){
 $stmt -> execute();
 $stmt -> bind_result($id, $title, $url,$img, $op);

 
	echo "<table>";
	echo "<tr><td>Slett</td><td>Tittel</td><td>URL</td><td>Bilde</td><td>Eier</td></tr>\n";
	//loope gjennom radene i studenkel_content
	while ($stmt->fetch()){
	echo "<tr><td><a href=\"del.php?id=".$id."\" onclick=\"return confirm('Er du sikker?')\">[delete]</a></td><td>$title</td><td>$url</td><td>$img</td><td>$op</td></tr>\n";
	}
 $stmt -> close();
 }
 
 echo "</table><br>";
     /* Close connection */
   $mysqli -> close();
}

/*
 ######################################################################################
 SLETT LINK
 ######################################################################################
*/
function deleteLink($id){
global $mysqli;
connect();
 
 // Finn filnavnet på bildet som hører til id
  if($stmt = $mysqli -> prepare("SELECT img FROM studenkel_content where id=?")){
  $stmt -> bind_param("i", $id); // id er typ Integer (i)
 $stmt -> execute();
 $stmt -> bind_result($img);
  $stmt -> fetch();
 $stmt -> close();
 
 //die("Debug: Attempting to delete image: images/$img with id: $id");
 // Slett bildet
unlink("images/".$img);
 }
 else {
 die($mysqli->error);
 }
 
 // Slett raden fra studenkel_content
 if($stmt = $mysqli -> prepare("DELETE FROM studenkel_content WHERE id=?")){
 $stmt -> bind_param("i", $id); // id er typ Integer (i)
 $stmt -> execute();
 $stmt -> close();
 
 
 header("Location: admin.php");
 // mulig legge på en ?msg="LINK SLETTET". els.

 }
 else {
 echo("SQL fuckup: ".$mysqli->error);
 }
 
     /* Close connection */
   $mysqli -> close();

}


//######################################################################################
// saveLink - Lagre link i databasen
//Eirik 9/20/2013 9:28
//######################################################################################

function saveLink($title, $url, $group, $img, $user, $desc){
global $mysqli;
 connect();
 
 
  // group er reserved keyword i SQL... tok bare 3 timer å finne ut av DET! renama til gruppe
  //Update studenkel_content
  if($stmt = $mysqli -> prepare("INSERT into studenkel_content(title,url,gruppe,op,img,description) VALUES(?, ?, ?, ?, ?, ?)")){
	$stmt -> bind_param("ssssss", $title, $url, $group, $user, $img,$desc);
	$stmt -> execute();
	$stmt -> close();
	}
	else {
	die( "SQL syntax fucked: ".$mysqli->error."<br>" );
	}
	
  
     /* Close connection */
   $mysqli -> close();
  echo "Saved link: $title ($url) to group: $group with image: $img. OP: $user<br>";

}


//######################################################################################
// saveSkin - Lagre Skin navn i databasen - brukes i skingen.php ( skin generatoren )
//Eirik 7. nov 13:23
//######################################################################################

function saveSkin($name, $creator){
global $mysqli;
 connect();

//Sjekk om navnet eksisterer fra før

$stmt = $mysqli -> prepare("SELECT id from studenkel_skins where name=?");
$stmt -> bind_param("s", $name);
$stmt -> execute();
$stmt -> bind_result($result);
$stmt -> fetch();
$stmt -> close();
if($result == 0) {

  if($stmt = $mysqli -> prepare("INSERT into studenkel_skins(name, creator) VALUES(?, ?)")){
	$stmt -> bind_param("ss", $name, $creator);
	$stmt -> execute();
	$stmt -> close();
	}
	else {
	die( "SQL syntax fucked(saveSkin): ".$mysqli->error."<br>" );
	}
	return 1;	
  }
else {
return -1;
}

     /* Close connection */
   $mysqli -> close();
}



/* ####################################################################
####                     Log funksjon, for å logge aktivitet. NSA-STYLE 							###########
*/ ####################################################################
function NSAlog($user, $action){
global $mysqli;
 connect();
 $ip = $_SERVER['REMOTE_ADDR'];
 $date = strtotime(date('d-m-Y H:i:s')); // timestamp i datetime format ( integer)
 
  if($stmt = $mysqli -> prepare("INSERT into studenkel_log(user, date, action, ip) VALUES(?, FROM_UNIXTIME(?), ?, ?)")){
	$stmt -> bind_param("siss", $user, $date, $action, $ip);
	$stmt -> execute();
	$stmt -> close();
	}
	else {
	die( "SQL syntax fucked, NSA LOGGER DISABLED! ----> ".$mysqli->error."<br>" );
	}
	
  
     /* Close connection */
   $mysqli -> close();

}


/*
 ######################################################################################
 REGISTRER NY BRUKER
 ######################################################################################
*/
function register($user, $pass, $email){
global $mysqli;

//connect to Mysqli DB
connect();

//Sjekk om brukernavnet er tatt

$stmt = $mysqli -> prepare("SELECT id from studenkel_users where username=?");
$stmt -> bind_param("s", $user);
$stmt -> execute();
$stmt -> bind_result($result);
$stmt -> fetch();
$stmt -> close();

// hvis resultatet er 0, så betyr det at ingen rader i tabellen matchet med brukernavnet, og det er ledig.
if($result == 0) { //$result er id fra studenkel_users
echo "Brukernavnet er tilgjengelig<br>";


   /* Create a prepared statement */
   if($stmt = $mysqli -> prepare("INSERT INTO studenkel_users(username,password,email,skin) VALUES(?,OLD_PASSWORD(?),?,'default')")) {
	// PASSWORD() krypterer passordet, så det ikke blir lagret i plaintext.
   
	
      /* Bind parameters */
	  //binder brukernavn og passord til spørsmåltegnene i prepare SQLen.
      $stmt -> bind_param("sss", $user, $pass, $email);
	  /* Execute it */
	  $stmt -> execute();
	  /* Close statement */
      $stmt -> close();

	// Oppdater studenkel_userprefs, legg til alle linker.
	// Start-pakke.
		$pack = array(4, 19, 14, 27, 28, 17, 18, 20, 48, 60, 30, 38, 53, 57, 33, 34, 35, 36, 37, 39, 40, 43);
		
		if($stmt = $mysqli -> prepare("INSERT into studenkel_userprefs(usr,linkid) VALUES(?, ?)")){
		
		foreach($pack as $lenke){
		$stmt -> bind_param("si", $user, $lenke);
		$stmt -> execute();
		}
		$stmt -> close();
		}	

		// lage raden i studenkel_profileinfo
		if($stmt = $mysqli -> prepare("INSERT INTO studenkel_userprofile(user)VALUE ( ? )")){
		$stmt -> bind_param("s", $user);
		$stmt -> execute();
		$stmt -> close();
		}
		$mysqli -> close();

      echo "Bruker oprettet: ".$user. "<br>";
	  echo "<a href=\"index.php\">Du kan nå logge inn</a>";

  
	  	  // NSA WAS HERE
	  NSAlog($user, "Oprettet bruker");
	  header( 'Location: reg_complete.php' ) ;
   }
}

//om $result ikke er 0, er brukernavnet allerede tatt. 
else {
echo "Brukernavnet $user er allerede tatt...<a href=register.php>Tilbake</a>";

}
				
} 

function saveprofile($info, $user, $studie, $img, $fornavn, $etternavn, $hjemmeside){
global $mysqli;
connect();
 
 if($stmt = $mysqli -> prepare("UPDATE studenkel_userprofile SET om_meg = ?, studieretning = ?, bilde = ?, fornavn = ?, etternavn = ?, hjemmeside = ? WHERE user = ?")) {
	$stmt -> bind_param("sssssss", $info, $studie, $img, $fornavn, $etternavn, $hjemmeside, $user);
	$stmt -> execute();
	$stmt -> close();
 echo 'Profilen din er blitt oppdatert';
}
 else {
 die($mysqli->error);
 }
 
 
     /* Close connection */
   $mysqli -> close();

}

function changeEmail($old, $new){
global $mysqli;
connect();
$user = $_SESSION['user']; 

  if($stmt = $mysqli -> prepare("UPDATE studenkel_users SET email=? where email=? AND username=?")){
  $stmt -> bind_param("sss", $new, $old, $user); // id er typ Integer (i)
 $stmt -> execute();
 $stmt -> close();
 //echo "SQL: UPDATE studenkel_users SET email=$new where email=$old";
 echo "Mailen er byttet til $new<br>";
}
 else {
 die($mysqli->error);
 }
 
 
     /* Close connection */
   $mysqli -> close();

}
/*

 Glemt passord funksjon
*/
function glemt_passord($email, $nyttpw){
global $mysqli;
connect();
$id = -1;
 
 // sjekk om email stemmer
   if($stmt = $mysqli -> prepare("SELECT id FROM studenkel_users WHERE email=?")){
  $stmt -> bind_param("s", $email); 
  $stmt -> execute();
$stmt -> bind_result($id);
 $stmt -> fetch();
 $stmt -> close(); 

 }
 else {
 echo "fuckup: ".$mysqli->error;
 }

	if($id > 0) {
 
  if($stmt = $mysqli -> prepare("UPDATE studenkel_users SET password=OLD_PASSWORD(?) WHERE id=?")){
  $stmt -> bind_param("ss", $nyttpw, $id); 
 $stmt -> execute();
 $stmt -> close();

echo "Nytt passord er sendt til din epost";
// The message
$message = "Ditt nye passord på Studenkel er $nyttpw\r\n Klikk her for å logge inn: http://studenkel.zapto.org/s/index.php";

// Send
mail($email, 'Nytt passord på Studenkel', $message, "From: info@studenkel.zapto.org");

 }
 else {
 die($mysqli->error);
 }
 
  }
  else {
  echo "Epost addressen finnes ikke..";
  }
  
     /* Close connection */
   $mysqli -> close();
   
}


/*
 Bytte passord funksjon
*/
function changePassword($user, $old, $new){
global $mysqli;
connect();
 
 //Sjekk at det gamle passordet stemmer
 if(login($user, $old) > 0){
 
 
  if($stmt = $mysqli -> prepare("UPDATE studenkel_users SET password=OLD_PASSWORD(?) where username=? AND password=OLD_PASSWORD(?)")){
  $stmt -> bind_param("sss", $new, $user, $old); 
 $stmt -> execute();
 $stmt -> close();
 //echo "SQL: UPDATE studenkel_users SET email=$new where email=$old";
 echo "<span style='color:green; font-size:20px'>Passord byttet!</span><br>";
}
 else {
 die($mysqli->error);
 }
      /* Close connection */
   $mysqli -> close();
   
   }
   // gammelt passord stemmer ikke
   else {
   echo "<span style='color:red; font-size:20px'>Passordet ditt er ikke riktig!</span>";
   }

}

/*
 Sette skin i studenkel_users når bruker velger et tema.
*/
function changeSkin($user, $skin){
global $mysqli;
connect();
 

  if($stmt = $mysqli -> prepare("UPDATE studenkel_users SET skin=? where username=?")){
  $stmt -> bind_param("ss", $skin, $user); 
 $stmt -> execute();
 $stmt -> close();
}
 else {
 die($mysqli->error);
 }
 
 
     /* Close connection */
   $mysqli -> close();
   

}

/*
getSkin() returnerer skin fra DB
*/
function getSkin($user){
global $mysqli;
connect();

	if($stmt = $mysqli -> prepare("SELECT skin FROM studenkel_users where username=?")){
	$stmt -> bind_param("s", $user); 
	$stmt -> execute();
	$stmt -> bind_result($result);
	$stmt -> fetch();
	$stmt -> close();
	
}
 else {
 die("Error i getSkin():: ".$mysqli->error);
 }
 
	return $result; //returnerer skin varchar fra studenkel_user.
     /* Close connection */
   $mysqli -> close(); //lukker koblingen til databasen.
   
}



?>
